package logic

import (
	"errors"
	"gvb-server/Request"
	"gvb-server/global"
	"gvb-server/models"
	"gvb-server/utils"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"

	"golang.org/x/crypto/bcrypt"
)

type LoginResponse struct {
	Token          string `json:"token"`
	UUID           uint   `json:"uuid"`
	ExpressionAt   string `json:"expression_at"`
	ExpressionTime string `json:"expression_time"`
}

func (u User) Login(ctx *gin.Context, data *Request.UserLoginData) (LoginResponse, error) {
	var loginResponse LoginResponse
	var user models.Users
	err := global.DB.Model(models.Users{}).Where("user_name = ? and status = 1 ", data.Username).First(&user).Error
	if err != nil {
		return loginResponse, errors.New("用户名或密码错误")
	}

	if err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(data.Password)); err != nil {
		return loginResponse, errors.New("用户名或密码错误")
	}

	loginResponse.Token = utils.GenerateRandomStringMath(32)
	loginResponse.UUID = user.ID
	loginResponse.ExpressionAt = time.Now().Format(time.DateTime)
	loginResponse.ExpressionTime = strconv.Itoa(int(global.Config.Jwt.Expires))
	go func() {
		user.Token = loginResponse.Token
		user.IP = ctx.RemoteIP()
		global.DB.Model(models.Users{}).Updates(&user)
	}()
	return loginResponse, nil
}
